<template>
  <div class="header-container">
    <nav-bar
      :title="'订单管理'"
      :showLeftArrow="true"
      :leftText="'返回'"
      @click-left="back"
    >
    </nav-bar>
  </div>
  <div class="main-container">
    <van-tabs v-model:active="activeTab" @change="onChangeTab">
      <van-tab title="全部" :name="'ALL'"></van-tab>
      <van-tab title="待付款" :name="orderStatus.UNPAID"></van-tab>
      <van-tab title="待发货" :name="orderStatus.UN_EXPRESSED"></van-tab>
      <van-tab title="已收货" :name="orderStatus.RECEIVED"></van-tab>
      <van-tab title="待收货" :name="orderStatus.EXPRESSED"></van-tab>
      <van-tab title="已完成" :name="orderStatus.COMPLETE"></van-tab>
      <van-tab title="已关闭" :name="orderStatus.CLOSED"></van-tab>
    </van-tabs>
    <van-pull-refresh v-model="pullRefreshLoading" @refresh="onPullRefresh">
      <van-list
        v-model:loading="listLoading"
        :finished="listFinished"
        finished-text="没有更多了"
        @load="onListLoad"
      >
        <template v-if="orders && orders.length > 0">
          <div
            v-for="order in orders"
            :key="order.id"
            class="order-item-box"
            @click="goToDetail(order)"
          >
            <div class="order-item-header" style="">
              <span> 订单时间：{{ order.orderTime }} </span>
              <span>
                <van-tag
                  v-if="order.orderStatus == orderStatus.UNPAID"
                  color="cyan"
                >
                  待付款
                </van-tag>
                <van-tag
                  v-if="order.orderStatus == orderStatus.UN_EXPRESSED"
                  color="blue"
                >
                  待发货
                </van-tag>
                <van-tag
                  v-if="order.orderStatus == orderStatus.EXPRESSED"
                  color="pink"
                >
                  待收货
                </van-tag>
                <van-tag
                  v-if="order.orderStatus == orderStatus.RECEIVED"
                  color="purple"
                >
                  已收货
                </van-tag>
                <van-tag
                  v-if="order.orderStatus == orderStatus.COMPLETE"
                  color="green"
                >
                  已完成
                </van-tag>
                <van-tag
                  v-if="order.orderStatus == orderStatus.CLOSED"
                  color="red"
                >
                  已关闭
                </van-tag>
              </span>
            </div>
            <van-card
              v-for="item in order.items"
              :key="item.id"
              :title="item.productName"
              :price="item.price"
              :thumb="item.productImgUrl"
              :num="item.quantity"
            />
          </div>
        </template>
        <template v-else>
          <van-empty />
        </template>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import NavBar from "@/components/NavBar.vue";
import TabBar from "@/components/TabBar.vue";
import { useRouter } from "vue-router";
import OmsOrder from "@/entity/OmsOrder";
import orderService from "@/services/order.service";
import { Page } from "@/entity/Page";
import { AxiosError } from "axios";
import { Toast } from "vant";
import OrderStatus from "@/entity/OmsOrderStatus";
import OrderQueryParam from "@/entity/OrderQueryParam";

type StateType = {
  page?: Page<OmsOrder> | null;
  orders: OmsOrder[];
  listLoading: boolean;
  listFinished: boolean;
  pullRefreshLoading: boolean;
  activeTab?: string | null | number;
  queryParam: OrderQueryParam;
};

export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const orderStatus = OrderStatus;
    const router = useRouter();
    const state = reactive<StateType>({
      page: new Page(),
      orders: [],
      listLoading: false,
      listFinished: false,
      pullRefreshLoading: false,
      activeTab: 0,
      queryParam: {},
    });

    onMounted(async () => {
      load();
    });

    const load = async (queryParam?: OrderQueryParam) => {
      try {
        state.listLoading = true;
        const page = await orderService.query(queryParam);
        state.page = page;

        state.queryParam.page = page.number + 1;
        state.queryParam.size = page.size;

        state.orders = [...state.page.content];
        state.listFinished = state.page.last;
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
        state.listLoading = false;
      }
    };

    const back = () => {
      router.push("/mine");
    };

    const onListLoad = () => {
      load(state.queryParam);
    };

    const goToDetail = (order: OmsOrder) => {
      router.push({
        path: "/order-detail",
        query: {
          id: order.id,
        },
      });
    };

    const onPullRefresh = async () => {
      try {
        state.pullRefreshLoading = true;
        await load(state.queryParam);
      } catch (e) {
        throw e;
      } finally {
        state.pullRefreshLoading = false;
      }
    };

    const onChangeTab = (name: string) => {
      if (name == "ALL") {
        delete state.queryParam.orderStatus;
      } else {
        state.queryParam.orderStatus = name as OrderStatus;
      }
      state.queryParam.page = 1;
      load(state.queryParam);
    };

    return {
      orderStatus,
      ...toRefs(state),
      back,
      onListLoad,
      goToDetail,
      onPullRefresh,
      onChangeTab,
    };
  },
});
</script>

<style scoped>
.order-item-box {
  /* margin: 20px 10px; */
  background-color: #fff;
}

.order-item-header {
  padding: 10px 20px 0 20px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.van-card {
  background-color: #fff;
  margin-top: 0;
}
</style>
